package com.cloud.async.flow.web.client;



import com.cloud.async.flow.callback.IGroupCallback;
import com.cloud.async.flow.web.tx.TransactionSource;
import com.cloud.async.flow.wrapper.WorkerWrapper;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

/**
 * 类入口，可以根据自己情况调整core线程的数量
 * @author chengr
 * @version 1.0
 */
public class FlowTemplate extends  AbstractFlow {

    /**
     *  线程池构造
     * @param executorService
     */
    public FlowTemplate(ExecutorService executorService) {
        this.executorService = executorService;
    }

    /**
     *  事务构造
     * @param executorService
     * @param transactionSource
     */
    public FlowTemplate(ExecutorService executorService, TransactionSource transactionSource) {
        this.executorService = executorService;
        this.transactionSource = transactionSource;
    }


    /**
     * 同步阻塞,直到所有都完成,或失败
     * @param timeout
     * @param workerWrapper
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public  boolean startWork(long timeout, WorkerWrapper... workerWrapper) throws ExecutionException, InterruptedException {
        return beginWork(timeout, workerWrapper);
    }

    /**
     * 同步阻塞,直到所有都完成,或失败 （带事务）
     * 事务特性ACID:
     * 隔离性（Isolation）:两个事务操作之间应相互不干扰
     * ......
     * 方法值只做一个验证，不推荐使用
     * @param timeout
     * @param workerWrapper
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Deprecated
    public  boolean startTransaction(long timeout, WorkerWrapper ...  workerWrapper) throws ExecutionException {
        if (workerWrapper == null || workerWrapper.length == 0) {
            return false;
        }
        List<WorkerWrapper> workerWrappers = Arrays.stream(workerWrapper).collect(Collectors.toList());
        return beginTransactionWork(timeout, workerWrappers);
    }

    /**
     * 异步执行,直到所有都完成,或失败后，发起回调
     * @param timeout
     * @param groupCallback
     * @param workerWrapper
     */
    public  void startWorkAsync(long timeout, IGroupCallback groupCallback, WorkerWrapper... workerWrapper) {
        beginWorkAsync(timeout, groupCallback, workerWrapper);
    }
}
